package logic

import (
	"context"
	"fmt"
	"product-mall/models/cache"
	"product-mall/models/mysql"
	"product-mall/pkg"

	"product-mall/productrpc/internal/svc"
	"product-mall/productrpc/productrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *productrpc.LoginRequest) (*productrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("account = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("账号未注册,请先注册后登录")
	}

	if in.Password == "" {
		get := cache.Rdb.Get(l.ctx, "sendSms"+"login"+in.Mobile)
		if get.Val() != in.CaptSms {
			return nil, fmt.Errorf("短信验证码错误,请重新输入")
		}
	} else {
		if user.Password != pkg.Md5(in.Password) {
			return nil, fmt.Errorf("密码错误,请重新输入")
		}
	}

	//成功后清除短信验证码缓存
	cache.Rdb.Del(l.ctx, "sendSms"+"login"+in.Mobile)
	return &productrpc.LoginResponse{UserId: int64(user.ID)}, nil
}
